<template>
  <div class="app-container flex p-8 flex-col">
    <!-- 搜索区 -->
    <div>
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="产品名称" prop="productName">
          <el-input
            v-noSpace
            v-model="queryParams.productName"
            placeholder="请输入产品名称"
            clearable
            style="width: 170px"
            @keyup.enter="getProductList"
          />
        </el-form-item>

        <el-form-item label="产品类别" prop="categoryCode">
          <el-select
            v-model="queryParams.categoryCode"
            placeholder="请选择产品类别"
            style="width: 170px"
            clearable
            filterable
            @change="getProductList"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="包装方式" prop="packageType">
          <el-select
            v-model="queryParams.packageType"
            placeholder="请选择包装方式"
            style="width: 170px"
            clearable
            @change="getProductList"
          >
            <el-option
              v-for="item in packageTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="search" @click="getProductList">搜索</el-button>
          <el-button icon="refresh" @click="handleReset">重置</el-button>
        </el-form-item>
        <el-form-item>
          <el-checkbox-group
            prop="categoryCodes"
            v-model="queryParams.categoryCodes"
            v-loading.fullscreen.lock="fullscreenLoading"
            @change="getProductList"
          >
            <el-checkbox
              :label="item.label"
              :value="item.value"
              v-for="(item, index) in options"
              :key="index"
            />
          </el-checkbox-group>
        </el-form-item>
      </el-form>
    </div>
    <!-- 内容区 -->
    <main class="flex-1">
      <!-- 商品列表 -->
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-5 gap-6" v-if="!!products?.length">
        <el-card
          shadow="hover"
          v-for="(product, index) in products"
          :key="index"
          class="bg-white rounded-lg shadow-sm transition-transform duration-300 cursor-pointer b-r"
          @click="
            () => {
              currentProduct = product;
              showProductDetail = true;
            }
          "
        >
          <div class="space-y-4">
            <!-- 产品图片 -->
            <div class="relative overflow-hidden">
              <el-carousel
                height="200px"
                motion-blur
                v-if="product.image.length"
                indicator-position="none"
              >
                <el-carousel-item
                  v-for="(item, index) in product.image"
                  :key="index"
                  height="200px"
                >
                  <uploadImage :url="item.url"></uploadImage>
                </el-carousel-item>
              </el-carousel>
              <el-carousel height="200px" arrow="never" v-else>
                <el-image fit="fill" loading="lazy" style="width: 100%; height: 100%">
                  <template #error>
                    <div class="image-slot">
                      <el-icon><icon-picture /></el-icon>
                    </div>
                  </template>
                </el-image>
              </el-carousel>
            </div>
            <!-- 产品信息 -->
            <div>
              <div class="text-lg font-medium">{{ product.productName }}</div>
              <div class="text-sm text-gray-600">产品类型：{{ product.categoryName }}</div>
              <div class="text-sm text-gray-600">包装方式：{{ product.packageType }}</div>
              <div class="text-sm text-gray-600">产品规格：{{ product.packageSize }}</div>
            </div>
            <div class="space-y-3">
              <div class="text-red-500 text-xl font-medium">¥{{ product.unitPrice }}</div>
              <div class="flex items-center space-x-4">
                <el-button
                  type="primary"
                  class="flex-1 bg-blue-500 text-white py-2 cursor-pointer whitespace-nowrap hover:bg-blue-600"
                  @click.stop="handleAddToCart(product)"
                >
                  加入购物车
                </el-button>
              </div>
            </div>
          </div>
        </el-card>
      </div>

      <el-empty v-else description="暂无商品" />
      <div class="float-right">
        <pagination
          v-if="total > 0"
          v-model:total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getProductList"
        />
      </div>
      <div></div>
    </main>
    <!-- 购物车 -->
    <el-dialog v-model="showCart" @close="handleCartClose">
      <div class="bg-white shadow-sm z-50">
        <div class="max-w-7xl mx-auto px-4 h-16 flex items-center justify-between">
          <h1 class="text-xl font-medium">购物车</h1>
          <div v-if="myCart.products.length > 0">
            <el-button link type="primary" v-if="!isManager" @click="myCart.batchRemove()">
              删除
            </el-button>
            <el-button
              link
              type="primary"
              @click="
                () => {
                  isManager = !isManager;
                }
              "
            >
              {{ isManager ? "管理" : "关闭" }}
            </el-button>
          </div>
        </div>
      </div>

      <div class="max-w-7xl mx-auto px-4">
        <!-- 空购物车状态 -->
        <div v-if="myCart.products.length === 0" class="text-center py-20">
          <el-empty description="购物车还是空的，去挑选心仪的商品吧" />
        </div>

        <!-- 购物车列表 -->
        <div v-else>
          <el-scrollbar height="400px">
            <div class="bg-white rounded-lg p-4 border">
              <div
                v-for="(item, index) in myCart.products"
                :key="index"
                class="flex items-center items-start py-4 border-b last:border-0 relative"
              >
                <el-checkbox v-if="!isManager" v-model:model-value="item.isChecked" />
                <div class="relative overflow-hidden ml-4">
                  <el-carousel
                    class="w-32 h-32"
                    width="100%"
                    height="100%"
                    motion-blur
                    indicator-position="none"
                    v-if="item.image.length"
                  >
                    <el-carousel-item v-for="p in item.image" :key="p.url">
                      <uploadImage :url="p.url"></uploadImage>
                    </el-carousel-item>
                  </el-carousel>
                  <el-carousel
                    class="w-32 h-32"
                    width="100%"
                    height="100%"
                    motion-blur
                    arrow="never"
                    v-else
                  >
                    <el-image fit="fill" loading="lazy" style="width: 100%; height: 100%">
                      <template #error>
                        <div class="image-slot">
                          <el-icon><icon-picture /></el-icon>
                        </div>
                      </template>
                    </el-image>
                  </el-carousel>
                </div>
                <!-- 产品信息 -->
                <div class="flex-1 ml-4">
                  <div class="text-lg font-medium">{{ item.productName }}</div>
                  <div class="text-sm text-gray-600">产品编号：{{ item.productCode }}</div>
                  <div class="text-sm text-gray-600">产品规格：{{ item.packageSize }}</div>
                  <div class="text-sm text-gray-600">包装方式：{{ item.packageType }}</div>

                  <div class="text-sm text-gray-600">产品类型：{{ item.categoryName }}</div>
                </div>
                <div class="flex-1 ml-4">
                  <div class="flex items-center justify-between mt-2">
                    <div class="text-xl">¥{{ item.getTotalPrice().toFixed(2) }}</div>
                    <div class="flex items-center">
                      <el-button class="w-8 h-8 whitespace-nowrap" @click="myCart.decrement(item)">
                        -
                      </el-button>
                      <span class="w-12 text-center">{{ item.qty }}</span>
                      <el-button class="w-8 h-8 whitespace-nowrap" @click="myCart.increment(item)">
                        +
                      </el-button>
                    </div>
                  </div>
                </div>
                <el-button
                  icon="Delete"
                  link
                  type="danger"
                  class="absolute right-0 top-2"
                  @click="myCart.removeItem(item)"
                ></el-button>
              </div>
            </div>
          </el-scrollbar>
          <!-- 底部结算栏 -->
          <div class="bg-white shadow-up-lg">
            <div class="max-w-7xl mx-auto px-4 h-16 flex items-center justify-between">
              <div class="flex items-center">
                <!-- <el-checkbox v-model="allSelected" @change="toggleAllItems">全选</el-checkbox> -->
                <div>
                  合计:
                  <span class="text-lg">¥{{ myCart.totalPrice.toFixed(2) }}</span>
                </div>
                <!-- <div class="ml-2">
                  折扣率:
                  <span class="text-lg">{{ discountRate.toFixed(2) }}%</span>
                </div>
                <div class="ml-2">
                  折后金额:
                  <span class="text-lg text-blue-600">
                    ¥{{ ((myCart.totalPrice * discountRate) / 100).toFixed(2) }}
                  </span>
                </div> -->
              </div>
              <div>
                <el-button type="success" @click="myCart.save()">
                  <el-icon class="mr-1"><Download /></el-icon>
                  保存购物车
                </el-button>
                <el-button type="danger" @click="myCart.clear()">
                  <el-icon class="mr-1"><CircleClose /></el-icon>
                  清空购物车
                </el-button>
                <el-button type="primary" @click="handleCheckOutOpen">结算</el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 我的订单 -->
    <el-dialog v-model="showOrderList" title="我的订单" width="800px" @close="handleCloseOrderList">
      <div class="max-w-7xl mx-auto px-4">
        <!-- 订单列表 -->
        <div v-if="orders.length > 0">
          <el-scrollbar height="400px">
            <div class="dialog-body flex-1 overflow-y-auto">
              <div
                v-for="order in orders"
                :key="order.id"
                class="order-item py-4 border-b last:border-b-0"
              >
                <div class="flex justify-between items-start mb-2">
                  <div>
                    <div class="flex items-center gap-3 mb-2">
                      <span class="text-gray-600">订单编号：</span>
                      <span>{{ order.orderCode }}</span>
                    </div>
                    <div class="flex items-center gap-3">
                      <span class="text-gray-600">下单时间：</span>
                      <span class="text-gray-600">{{ order.createTime }}</span>
                    </div>
                  </div>
                  <div class="flex items-center">
                    <el-tag v-if="order?.status == '0'" size="small" effect="plain" type="warning">
                      待审核
                    </el-tag>
                    <el-tag v-if="order?.status == '1'" size="small" effect="plain" type="danger">
                      审核拒绝
                    </el-tag>
                    <el-tag v-if="order?.status == '2'" size="small" effect="plain" type="success">
                      已审核
                    </el-tag>
                    <el-tag v-if="order?.status == '3'" size="small" effect="plain" type="success">
                      计划完成
                    </el-tag>
                    <el-tag v-if="order?.status == '4'" size="small" effect="plain" type="success">
                      生产完成
                    </el-tag>
                    <el-tag v-if="order?.status == '5'" size="small" effect="plain" type="success">
                      交付完成
                    </el-tag>
                    <el-tag v-if="order?.status == '6'" size="small" effect="plain" type="danger">
                      已退货
                    </el-tag>
                  </div>
                </div>
                <div class="flex justify-between items-center mt-3">
                  <div class="text-gray-600">
                    总金额：
                    <span class="text-primary font-medium">¥{{ order.totalPrice.toFixed(2) }}</span>
                  </div>
                  <div class="flex gap-4">
                    <el-button type="primary" link @click="viewOrderDetail(order)">
                      查看详情
                    </el-button>
                    <el-button
                      type="danger"
                      v-if="Number(order.status) < 2"
                      link
                      @click="cancelOrder(order)"
                    >
                      取消订单
                    </el-button>
                    <el-button
                      type="danger"
                      v-if="Number(order.status) >= 2"
                      link
                      @click="returnOrder(order)"
                    >
                      退货
                    </el-button>
                  </div>
                </div>
              </div>
            </div>
          </el-scrollbar>
        </div>
        <div v-else class="text-center py-20">
          <el-empty description="暂无订单" />
        </div>
      </div>
    </el-dialog>

    <!-- 订单详情 -->
    <el-dialog
      v-model="showOrderDetail"
      title="订单详情"
      width="800px"
      @close="handleCloseOrderDetail"
    >
      <div class="max-w-7xl mx-auto px-4">
        <div class="">
          <!-- 订单基本信息 -->
          <div class="bg-gray-50 rounded-lg p-6 mb-8 space-y-4">
            <div class="flex items-center">
              <span class="text-gray-500 w-[100px] font-medium">订单编号</span>
              <span class="text-gray-700 font-mono">{{ currentOrder?.orderCode }}</span>
            </div>
            <div class="flex items-center">
              <span class="text-gray-500 w-[100px] font-medium">订单状态</span>
              <el-tag
                ass="!px-4 !py-1 !text-sm !font-medium"
                v-if="currentOrder?.status == '0'"
                type="warning"
              >
                待审核
              </el-tag>
              <el-tag
                ass="!px-4 !py-1 !text-sm !font-medium"
                v-if="currentOrder?.status == '1'"
                type="danger"
              >
                审核拒绝
              </el-tag>
              <el-tag
                ass="!px-4 !py-1 !text-sm !font-medium"
                v-if="currentOrder?.status == '2'"
                type="success"
              >
                已审核
              </el-tag>
              <el-tag
                ass="!px-4 !py-1 !text-sm !font-medium"
                v-if="currentOrder?.status == '3'"
                type="success"
              >
                计划完成
              </el-tag>
              <el-tag
                ass="!px-4 !py-1 !text-sm !font-medium"
                v-if="currentOrder?.status == '4'"
                type="success"
              >
                生产完成
              </el-tag>
              <el-tag
                ass="!px-4 !py-1 !text-sm !font-medium"
                v-if="currentOrder?.status == '5'"
                type="success"
              >
                交付完成
              </el-tag>
              <el-tag
                ass="!px-4 !py-1 !text-sm !font-medium"
                v-if="currentOrder?.status == '6'"
                type="danger"
              >
                已退货
              </el-tag>
            </div>
            <div class="flex items-center">
              <span class="text-gray-500 w-[100px] font-medium">下单时间</span>
              <span class="text-gray-700">{{ currentOrder?.createTime }}</span>
            </div>
            <div class="flex items-center">
              <span class="text-gray-500 w-[100px] font-medium">总金额</span>
              <span class="text-red-500 text-xl font-semibold">
                ¥{{ currentOrder?.totalPrice.toFixed(2) }}
              </span>
            </div>
          </div>
          <!-- 商品列表 -->
          <div>
            <h3 class="text-lg font-semibold mb-6 text-gray-800">商品列表</h3>
            <div class="space-y-6">
              <!-- <el-carousel
                trigger="click"
                height="300"
                arrow="always"
                v-if="!!currentOrder?.products?.length"
              >
                <el-carousel-item v-for="product in currentOrder?.products" :key="product.id">
                  <div
                    class="flex bg-white rounded-xl p-6 border border-gray-100 hover:border-gray-200 transition-colors"
                  >
                    <div
                      class="w-[160px] h-[160px] bg-gray-50 rounded-lg overflow-hidden flex items-center justify-center"
                    >
                      <el-carousel
                        class="w-24 h-24"
                        width="100%"
                        height="100%"
                        motion-blur
                        indicator-position="none"
                      >
                        <el-carousel-item v-for="p in product?.image" :key="p.url">
                          <el-image :src="p.url" fit="fill" style="width: 100%; height: 100%">
                            <template #error>
                              <div class="image-slot">
                                <el-icon><icon-picture /></el-icon>
                              </div>
                            </template>
                          </el-image>
                        </el-carousel-item>
                      </el-carousel>
                    </div>

                    <div class="ml-6 flex-1">
                      <h4 class="text-xl font-semibold mb-4 text-gray-800">
                        {{ product?.productName }}
                      </h4>
                      <div class="grid grid-cols-2 gap-4">
                        <div class="flex items-center">
                          <span class="text-gray-500 w-[100px] font-medium">产品编号</span>
                          <span class="text-gray-700 font-mono">{{ product.productCode }}</span>
                        </div>
                        <div class="flex items-center">
                          <span class="text-gray-500 w-[100px] font-medium">类型</span>
                          <el-tag size="small" class="!bg-blue-50 !text-blue-600 !border-blue-100">
                            {{ product?.categoryName }}
                          </el-tag>
                        </div>
                        <div class="flex items-center">
                          <span class="text-gray-500 w-[100px] font-medium">规格</span>
                          <span class="text-gray-700">{{ product?.packageSize }}</span>
                        </div>
                        <div class="flex items-center">
                          <span class="text-gray-500 w-[100px] font-medium">包装方式</span>
                          <span class="text-gray-700">{{ product?.packageType }}</span>
                        </div>
                        <div class="flex items-center col-span-2">
                          <span class="text-gray-500 w-[100px] font-medium">价格</span>
                          <span class="text-red-500 text-lg font-semibold">
                            ¥{{ product?.unitPrice.toFixed(2) }}
                          </span>
                        </div>
                      </div>
                    </div>
                  </div>
                </el-carousel-item>
              </el-carousel> -->
              <div v-if="!!currentOrder?.products?.length">
                <el-table :data="currentOrder?.products">
                  <el-table-column label="商品名称" prop="productName"></el-table-column>
                  <el-table-column label="价格" prop="unitPrice"></el-table-column>
                  <el-table-column label="数量" prop="qty"></el-table-column>
                </el-table>
              </div>
              <div v-else class="flex items-center justify-center h-[300px]">
                <span class="text-gray-500">暂无商品</span>
                <el-icon class="ml-2" :size="18"><IconPicture /></el-icon>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 订单图标 -->
    <div class="fixed right-12 bottom-24 z-50 cursor-pointer" @click="handleOrderShow">
      <div class="relative">
        <el-badge :value="orders.length" :hidden="true" class="item">
          <div
            class="bg-black text-white p-2 shadow-lg hover:bg-dark transition-colors rounded-full flex items-center justify-center"
          >
            <el-icon :size="24"><Document /></el-icon>
          </div>
        </el-badge>
      </div>
    </div>
    <!-- 购物车图标 -->
    <div class="fixed right-12 bottom-12 z-50 cursor-pointer" @click="showCart = true">
      <div class="relative">
        <el-badge
          :value="myCart.products.length"
          :hidden="myCart.products.length === 0"
          class="item"
        >
          <div
            class="bg-black text-white p-2 shadow-lg hover:bg-dark transition-colors rounded-full flex items-center justify-center"
          >
            <el-icon :size="24"><ShoppingCartFull /></el-icon>
          </div>
        </el-badge>
      </div>
    </div>
    <!-- 查看商品详情 -->
    <el-dialog
      v-model="showProductDetail"
      title="商品详情"
      width="800px"
      @close="handleCloseProductDetail"
    >
      <div class="flex">
        <div class="w-1/2">
          <div class="relative overflow-hidden ml-4">
            <el-carousel
              height="200px"
              motion-blur
              v-if="currentProduct?.image.length"
              indicator-position="none"
            >
              <el-carousel-item
                v-for="(p, index) in currentProduct?.image"
                :key="index"
                height="200px"
              >
                <uploadImage :url="p.url"></uploadImage>
              </el-carousel-item>
            </el-carousel>
            <el-carousel height="200px" arrow="never" v-else>
              <el-image fit="fill" loading="lazy" style="width: 100%; height: 100%">
                <template #error>
                  <div class="image-slot">
                    <el-icon><icon-picture /></el-icon>
                  </div>
                </template>
              </el-image>
            </el-carousel>
          </div>
        </div>
        <div class="w-1/2 pl-6">
          <h2 class="text-xl font-medium mb-4">{{ currentProduct?.productName }}</h2>
          <p class="text-gray-600 mb-4">产品编号：{{ currentProduct?.productCode }}</p>
          <div class="space-y-4">
            <div class="flex justify-between">
              <span class="text-gray-600">类型</span>
              <span class="text-gray-500 font-medium">{{ currentProduct?.categoryName }}</span>
            </div>
          </div>
          <div class="space-y-4">
            <div class="flex justify-between">
              <span class="text-gray-600">规格</span>
              <span class="text-gray-500 font-medium">{{ currentProduct?.packageSize }}</span>
            </div>
          </div>
          <div class="space-y-4">
            <div class="flex justify-between">
              <span class="text-gray-600">包装方式</span>
              <span class="text-gray-500 font-medium">{{ currentProduct?.packageType }}</span>
            </div>
          </div>
          <div class="space-y-4">
            <div class="flex justify-between">
              <span class="text-gray-600">价格</span>
              <span class="text-red-500 font-medium">¥{{ currentProduct?.unitPrice }}</span>
            </div>
          </div>
          <div class="space-y-4">
            <div class="flex justify-start">
              <el-tag v-for="label in currentProduct?.labels" class="mr-2">
                {{ label.labelName }}:{{ label.labelValue }}
              </el-tag>
            </div>
          </div>
          <div class="mt-6 space-x-4">
            <el-input-number v-model="orderQuantity" :min="1" />
            <el-button
              type="primary"
              class="bg-blue-500 text-white px-6 py-2 !rounded-button whitespace-nowrap"
              @click="
                () => {
                  handleAddToCart(currentProduct, orderQuantity);

                  showProductDetail = false;
                }
              "
            >
              加入购物车
            </el-button>
          </div>
        </div>
      </div>
    </el-dialog>
    <!-- 结算弹窗 -->
    <el-dialog v-model="showCheckout" title="结算订单" width="800px" @close="handleCloseCheckout">
      <el-form ref="dialogFormDataRef" :model="dialogFormData" label-width="120px" :rules="rules">
        <el-row>
          <el-col :span="12">
            <el-form-item label="客户名称" prop="customerName">
              <el-input
                v-noSpace
                disabled
                v-model="dialogFormData.customerName"
                placeholder="请输入客户名称"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="联系人" prop="contactPerson">
              <el-select
                v-model="dialogFormData.contactPerson"
                placeholder="请选择联系人"
                clearable
                @change="changeContactPerson"
              >
                <el-option
                  v-for="item in contactList"
                  :key="item.id"
                  :label="item.contactPerson"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人电话" prop="contactPhone">
              <el-input
                v-noSpace
                v-model="dialogFormData.contactPhone"
                placeholder="请输入联系人电话"
                disabled
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="送货日期" prop="deliveryDate">
              <el-date-picker
                v-model="dialogFormData.deliveryDate"
                type="date"
                placeholder="选择时间"
                value-format="YYYY-MM-DD"
                style="width: 100%"
                clearable
                :disabled-date="disabledDate"
              />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="送货地址" prop="address">
              <el-select
                v-model="dialogFormData.address"
                placeholder="请选择送货地址"
                clearable
                filterable
              >
                <el-option
                  v-for="item in addressList"
                  :key="item.code"
                  :label="item.address"
                  :value="item.code"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button
          type="primary"
          @click="
            () => {
              myCart.checkout();
            }
          "
        >
          确定
        </el-button>
      </template>
    </el-dialog>
    <!-- 退货弹窗 -->
    <el-dialog title="退货" width="800px" @close="handleCloseReturn" v-model="showReturn">
      <el-form ref="returnDialogFormDataRef" :model="returnDialogFormData" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="销售订单编号" prop="code">
              <el-input
                v-noSpace
                v-model="returnDialogFormData.code"
                placeholder="请选择销售订单编号"
                disabled
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户名称">
              <el-input
                v-noSpace
                v-model="returnDialogFormData.customerName"
                placeholder="请输入客户名称"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户编号" prop="companyCode">
              <el-input
                v-noSpace
                v-model="returnDialogFormData.companyCode"
                placeholder="请输入客户编号"
                disabled
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="退货方式" prop="returnMethod">
              <el-select v-model="returnDialogFormData.returnMethod" placeholder="全部" clearable>
                <el-option label="退货退款" :value="'1'" />
                <el-option label="只退货" :value="'2'" />
                <el-option label="报废退货" :value="'3'" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="returnDialogFormData.returnMethod !== '2'">
            <el-form-item label="折扣率" prop="discountRate">
              <el-input v-model="discountRate" disabled placeholder="请输入折扣率" class="!w-full">
                <template #suffix>%</template>
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-noSpace
                v-model="returnDialogFormData.remark"
                :rows="4"
                type="textarea"
                placeholder="请输入备注"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-divider />

      <!-- <el-form
        ref="returnDialogFormDataProRef"
        :model="returnDialogFormDataPro"
     
        label-width="120px"
        v-if="returnDialogFormData.returnMethod !== '3'"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="产品编号" prop="productCode">
              <el-input
                v-noSpace
                v-model="returnDialogFormDataPro.productCode"
                placeholder="请输入产品编号"
                disabled
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="产品名称" prop="productCode">
              <el-select
                v-model="returnDialogFormDataPro.productCode"
                placeholder="请选择产品名称"
                clearable
                filterable
                @change="changeReturnProduct"
                @visible-change="searchCode(returnDialogFormData.code)"
              >
                <el-option
                  v-for="item in returnProduct"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item :label="`数量（${unitFormat(dialogFormDataPro.unit) || ''}）`" prop="qty">
              <el-input-number
                v-model="productQty"
                :max="returnDialogFormDataPro.qty"
                :min="0"
                placeholder="请输入数量"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="单价" prop="unitPrice">
              <el-input-number
                v-model="returnDialogFormDataPro.unitPrice"
                disabled
                placeholder="请输入单价"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="rowRemark">
              <el-input
                v-noSpace
                v-model="returnDialogFormDataPro.rowRemark"
                :rows="2"
                type="textarea"
                placeholder="请输入备注"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" />
          <el-col :span="12">
            <el-form-item>
              <el-button type="primary" @click="handleSavePro('return')">添加退货产品</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form> -->

      <el-table :data="returnProductData" v-if="returnDialogFormData.returnMethod !== '3'">
        <el-table-column prop="productCode" label="产品编号" align="center" width="110" />
        <el-table-column prop="productName" label="产品名称" align="center" width="110" />

        <el-table-column label="每份数量" prop="qty" align="center">
          <template #default="scope">
            <div class="">
              {{ scope.row.qty }}
              {{ formatUnit(scope.row.unit) }}
            </div>
          </template>
        </el-table-column>

        <el-table-column label="单价(元)" prop="unitPrice" align="center" width="200" />

        <el-table-column prop="rowRemark" label="备注" show-overflow-tooltip align="center" />
        <el-table-column label="操作" fixed="right" width="70" align="center">
          <template #default="scope">
            <el-button type="danger" size="small" link @click="handleDelPro(scope.$index)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <template #footer>
        <div class="dialog-footer flex-center">
          <el-button @click="handleCloseReturn">取 消</el-button>

          <el-button v-debounce="handleReturn" type="primary">提 交</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import configApi, { ConfigType } from "@/api/config/config";
import cusInfoApi from "@/api/cusManage/cusInfo";
import cusInfo from "@/api/cusManage/cusInfo";
import SalesAPI, { SalesOrderInfo } from "@/api/order/sales";
import orderReturnAPI, { orderReturnInfo } from "@/api/orderReturn/orderReturn";
import productInfoAPI, { productInfoPageQuery } from "@/api/productInfo/productInfo";
import { Picture as IconPicture, ShoppingCartFull } from "@element-plus/icons-vue";
import { ElMessage, FormItemRule, FormRules } from "element-plus";
import { onMounted } from "vue";
import { formatUnit } from "@/utils/formatUnit";
let getUserInfo = JSON.parse(sessionStorage.getItem("USER_INFO") || "{}");
const showCheckout = ref(false);

//定义商品类
class Product {
  // id: number; // 产品ID
  productName: string; // 产品名称
  productCode: string; // 产品编号
  unitPrice: number; // 价格
  image: {
    name: string;
    url: string;
  }[]; // 图片
  description: string; // 描述
  qty: number; //订购数量
  packageSize: string; //包装规格
  packageType: string; //包装类型
  categoryName: string; //产品类型
  labels: {
    id: number;
    labelName: string;
    labelValue: string;
    productCode: string;
  }[]; //标签
  expireDay: string; //保质期
  unit: string; //单位

  isChecked: boolean = false; // 新增选中状态
  discountRate: number; //折扣率
  constructor(
    // id: number,
    productName: string,
    productCode: string,
    unitPrice: number,
    image: {
      name: string;
      url: string;
    }[],
    description: string,
    packageSize: string,
    packageType: string,
    expireDay: string,
    unit: string,
    categoryName: string,
    labels: {
      id: number;
      labelName: string;
      labelValue: string;
      productCode: string;
    }[],
    discountRate: number, //折扣率
    qty?: number
  ) {
    // this.id = id;
    this.productName = productName;
    this.productCode = productCode;
    this.unitPrice = unitPrice;
    this.image = image;
    this.description = description;
    this.packageSize = packageSize;
    this.categoryName = categoryName;
    this.labels = labels;
    this.expireDay = expireDay;
    this.unit = unit;
    this.qty = qty || 1;
    this.packageType = packageType;
    this.discountRate = discountRate;
  }

  getTotalPrice() {
    return this.unitPrice * this.qty;
  }
  increment() {
    this.qty++;
  }
  decrement() {
    if (this.qty > 0) this.qty--;
  }
  reset() {
    this.qty = 0;
  }
}

//定义购物车类
class Cart {
  products: Product[] = [];
  totalPrice: number = 0;

  addItem(item?: Product, qty: number = 1) {
    if (!item) return;
    const index = this.products.findIndex((p) => p.productCode === item.productCode);
    if (index !== -1) {
      this.products[index].qty += qty;
    } else {
      // 使用 reactive 包裹新商品
      this.products.push(
        reactive(
          new Product(
            // item.id,
            item.productName,
            item.productCode,
            item.unitPrice,
            item.image,
            item.description,
            item.packageSize,
            item.packageType,
            item.expireDay,
            item.unit,
            item.categoryName,
            item.labels,
            item.discountRate,
            qty
          )
        )
      );
    }
    this.updateTotalPrice();
    orderQuantity.value = 1;
  }
  removeItem(product: Product) {
    const index = this.products.findIndex((p) => p.productCode === product.productCode);
    if (index !== -1) {
      ElMessageBox.confirm("是否移出购物车列表", "Warning", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.products.splice(index, 1);
        this.updateTotalPrice();
        this.save(); // 增加保存逻辑
      });
    }
  }
  updateTotalPrice() {
    this.totalPrice = this.products.reduce((sum, product) => sum + product.getTotalPrice(), 0);
  }
  reset() {
    this.products.forEach((product) => product.reset());
    this.totalPrice = 0;
  }
  getTotalPrice() {
    return this.products.reduce((sum, product) => sum + product.getTotalPrice(), 0);
  }

  //保存购物车
  save() {
    sessionStorage.setItem(
      "cart",
      JSON.stringify({ cartProduct: this, userId: getUserInfo.userId })
    );
  }

  //减少数量
  decrement(product: Product) {
    const index = this.products.findIndex((p) => p.productCode === product.productCode);
    if (index !== -1) {
      if (this.products[index].qty === 1) {
        //是否确认
        return ElMessageBox.confirm("是否移出购物车列表", "Warning", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          this.products[index].decrement();
          this.products.splice(index, 1);
        });
      }
      this.products[index].decrement();
    }
    this.updateTotalPrice();
  }
  //增加数量
  increment(product: Product) {
    const index = this.products.findIndex((p) => p.productCode === product.productCode);
    if (index !== -1) {
      this.products[index].qty++; // ✅ 通过数组索引触发响应式
      this.updateTotalPrice();
    }
  }
  // 清空购物车
  clear() {
    ElMessageBox.confirm("是否清空购物车", "Warning", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    }).then(() => {
      this.products = [];
      this.totalPrice = 0;
      this.save();
    });
  }
  checkout() {
    //Todo..
    dialogFormDataRef.value?.validate((valid: boolean) => {
      if (!valid) return;
      // 新增一个订单对象
      addOrder(this.products).then(() => {
        this.products = [];
        this.totalPrice = 0;
        this.save();
        showCheckout.value = false;
        showCart.value = false;
        handleOrderShow();
      });
    });
  }

  //批量删除
  batchRemove() {
    ElMessageBox.confirm("确认删除选中商品？", "Warning", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    }).then(() => {
      this.products = this.products.filter((item) => !item.isChecked);
      this.updateTotalPrice();
      this.save();
    });
  }
}
const dialogFormDataRef = ref();
//加入购物车
const handleAddToCart = (product?: Product, qty?: number) => {
  if (contractStatus.value == "2") {
    return ElMessage.warning("合同审核未通过，无法下单");
  }
  if (contractStatus.value == "3") {
    return ElMessage.warning("合同异常终止，无法下单");
  }
  if (contractStatus.value == "4") {
    return ElMessage.warning("合同已到期，无法下单");
  }

  if (!product) return;
  myCart.addItem(product, qty);
  myCart.save();
  ElMessage.success("加入购物车成功");
};
//新增一个订单
const addOrder = useDebounceFn(async (product: Product[]) => {
  //获取登陆人信息

  let paramData: SalesOrderInfo = {
    docType: "0", // 订单类型
    companyCode: getUserInfo.companyCode, // 客户编号
    customerName: customerName.value, // 客户名称
    salesOrderDetailList: product, // 订单详情列表
    isReturnOrder: 0, // 是否为退货列表0否1是
    address: dialogFormData.address, // 地址
    shipCode: dialogFormData.address, // 地址
    contactPerson: dialogFormData.contactPerson, // 联系人
    contactPhone: dialogFormData.contactPhone,
    contractCode: contractCode.value, // 合同编号
    salesMan: salesMan.value, // 销售员
    deliveryDate: dialogFormData.deliveryDate, // 交货日期
    status: 0,
  };
  console.log(paramData, "paramData");

  await SalesAPI.saveOrUpdateTSalesOrder(paramData);
  ElMessage.success(`下单成功`);
}, 1000);

//实例化商品
const products = ref<Product[]>();
const myCart = reactive(new Cart());

//购物车弹窗
const showCart = ref(false);
//关闭
const handleCartClose = () => {
  // 清空选中状态
  myCart.products.forEach((item) => (item.isChecked = false));
  // 重置管理模式
  isManager.value = true;
  // 保存购物车状态（可选）
  myCart.save();
};
//是否管理
const isManager = ref(true);
//详情弹窗
const showProductDetail = ref(false);
//关闭
const handleCloseProductDetail = () => {
  showProductDetail.value = false;
  currentProduct.value = undefined;
  orderQuantity.value = 1;
};
//选择的产品
const currentProduct = ref<Product>();
const orderQuantity = ref<number>(1);

const queryFormRef = ref();
const queryParams = reactive<productInfoPageQuery>({
  pageNum: 1,
  pageSize: 20,
  productType: 1,
  categoryCodes: [],
});
// 包装类型下拉框选项
const packageTypeOptions = ref<{ value: string; label: string }[]>([]);

const getPackageType = () => {
  configApi.getConfigListByType(ConfigType.PACKAGE_TYPE).then((res) => {
    packageTypeOptions.value = res.map((item: any) => {
      return {
        value: item.codeValue,
        label: item.codeName,
      };
    });
  });
};

// 产品类型下拉框选项
const options = ref<{ value: string; label: string }[]>([]);

const getProductType = () => {
  productInfoAPI
    .getTypePage({ pageNum: 1, pageSize: 999 })
    .then((data) => {
      options.value = (data?.list || []).map((item: any) => ({
        value: item.code,
        label: item.name,
      }));
    })
    .finally(() => {});
};
//产品总数
const total = ref(0);
const fullscreenLoading = ref(false);
//获取产品列表
const getProductList = () => {
  fullscreenLoading.value = true;
  productInfoAPI
    .getPage(queryParams)
    .then((res) => {
      products.value = res.list.map((item: any) => {
        let image = JSON.parse(item.productImg || "[]");
        return reactive(
          new Product(
            // item.id,
            item.productName,
            item.code,
            item.price ? item.price : item.salesPrice,
            image,
            item.remark,
            item.packageSize,
            item.packageType,
            item.expireDay,
            item.unit,
            item.categoryName,
            item.labels,
            item.discountRate
          )
        );
      });
      total.value = res.total;
    })
    .finally(() => {
      fullscreenLoading.value = false;
    });
};

//重置
const handleReset = () => {
  queryFormRef.value.resetFields();
  queryParams.categoryCodes = [];
  getProductList();
};

// 订单类
class Order {
  id: number;
  orderCode: string;
  contractCode: string;
  salesMan: string;
  status: string;
  createTime: string;
  totalPrice: number;
  products: Product[];

  constructor(
    id: number,
    orderCode: string,
    status: string,
    createTime: string,
    totalPrice: number,
    products: Product[],
    contractCode: string,
    salesMan: string
  ) {
    this.id = id;
    this.orderCode = orderCode;
    this.status = status;
    this.createTime = createTime;
    this.totalPrice = totalPrice;
    this.products = products;
    this.contractCode = contractCode;
    this.salesMan = salesMan;
  }
  // //退货
  // returnOrder() {
  //   // 退货逻辑
  //   ElMessageBox.confirm("确定要退货吗？", "提示", {
  //     confirmButtonText: "确定",
  //     cancelButtonText: "取消",
  //     type: "warning",
  //   })
  //     .then(() => {
  //       // 退货操作逻辑，例如调用API进行退货处理等

  //       ElMessage.success("退货成功");
  //     })
  //     .catch(() => {});
  // }
}

// 订单列表
const orders = ref<Order[]>([]);
// 订单弹窗
const showOrderList = ref(false);
// 关闭订单列表
const handleCloseOrderList = () => {
  showOrderList.value = false;
};
// 订单详情弹窗
const showOrderDetail = ref(false);
// 当前订单
const currentOrder = ref<Order | null>(null);
// 查看订单详情
const viewOrderDetail = async (order: Order) => {
  currentOrder.value = order;
  showOrderDetail.value = true;
  const res = await getProductByOrder(order);
  currentOrder.value!.products = res.detailList;
};
// 关闭订单详情
const handleCloseOrderDetail = () => {
  showOrderDetail.value = false;
  currentOrder.value = null;
};

// 获取订单列表
const getOrderList = () => {
  console.log(getUserInfo, "getUserInfo.userId");
  if (!getUserInfo.companyCode) {
    ElMessage.error("该账号非商城账号，无法查看订单信息！");
    return;
  }

  SalesAPI.getPage({
    pageNum: 1,
    pageSize: 10,
    companyCode: getUserInfo.companyCode,
    isReturnOrder: 0,
  }).then((res) => {
    console.log(res);

    orders.value = res.list.map((item: any) => {
      return new Order(
        item.id,
        item.code,
        item.status,
        item.createTime,
        item.orderAmount,
        item.salesOrderDetailList,
        item.contractCode,
        item.salesMan
      );
    });
  });
};
//根据订单查产品
const getProductByOrder = (order: Order) => {
  return SalesAPI.getTSalesOrderDetailByCode(order.orderCode);
};

const customerName = ref("");

//根据code查名称
const getCustomerName = (code: string) => {
  cusInfo.getPage({ code: code, pageNum: 1, pageSize: 1 }).then((res: any) => {
    console.log(res, "res");
    customerName.value = res.records[0].companyName;
    getContractStatus(res.records[0].code);
  });
};
//合同
const contractCode = ref("");
//业务员
const salesMan = ref("");
//客户合同状态
const contractStatus = ref("");
//折扣率
const discountRate = ref(100);

//判断合同状态
const getContractStatus = (code: string) => {
  cusInfoApi.getContractList({ companyCode: code, pageNum: 1, pageSize: 10 }).then((res) => {
    console.log(res, "res");
    contractCode.value = res.list[0].code;
    salesMan.value = res.list[0].salesMan;
    contractStatus.value = res.list[0].status;
    discountRate.value = res.list[0].discountRate;
  });
};

const addressList = ref();
const contactList = ref();
// 根据code查联系人和地址
const getAdCtInfo = (code: string) => {
  cusInfoApi
    .getAddressPage({
      pageNum: 1,
      pageSize: 10,
      parentCode: code,
    })
    .then((res) => {
      addressList.value = res;
    });

  cusInfoApi
    .getContactPage({
      pageNum: 1,
      pageSize: 10,
      parentCode: code,
    })
    .then((res) => {
      contactList.value = res;
    });
};
//根据联系人查电话
const changeContactPerson = (val: any) => {
  dialogFormData.contactPhone = contactList.value.filter((ele: any) => {
    return ele.id == val;
  })[0].tel;
};
const disabledDate = (time: Date) => {
  const startDate = new Date();
  startDate.setHours(0, 0, 0, 0); // 设置开始日期为当天的开始时间
  return time.getTime() < startDate.getTime();
};
const rules = reactive<Record<string, FormItemRule[]>>({
  contactPerson: [{ required: true, message: "订单类型是必填项", trigger: "blur" }],
  salesMan: [{ required: true, message: "业务员是必填项", trigger: "blur" }],
  deliveryDate: [{ required: true, message: "送货日期是必填项", trigger: "blur" }],
  status: [{ required: true, message: "状态是必填项", trigger: "change" }],
  customerName: [{ required: true, message: "客户名称是必填项", trigger: "blur" }],
  address: [{ required: true, message: "客户地址是必填项", trigger: "blur" }],
});

const dialogFormData = reactive<{
  customerName: string;
  contactPerson: string;
  contactPhone: string;
  address: string;
  deliveryDate: string;
}>({
  customerName: customerName.value,
  contactPerson: "",
  contactPhone: "",
  address: "",
  deliveryDate: "",
});

const handleCheckOutOpen = () => {
  showCheckout.value = true;
  dialogFormData.customerName = customerName.value;
  getAdCtInfo(getUserInfo.companyCode);
};
const handleCloseCheckout = () => {
  showCheckout.value = false;
  dialogFormData.customerName = customerName.value;
  dialogFormData.contactPerson = "";
  dialogFormData.contactPhone = "";
  dialogFormData.address = "";
};
const handleOrderShow = () => {
  getOrderList();
  showOrderList.value = true;
};

//退货
const showReturn = ref(false);
const returnProductData = ref();

const handleCloseReturn = () => {
  showReturn.value = false;
  returnProductData.value = [];
  Object.assign(returnDialogFormData, {
    code: "",
    otherRef: "",
    docType: "",
    companyCode: "",
    customerName: "",
    discountRate: 0,
    discountAmount: 0,
    returnMethod: "1",
    remark: "",
    contractCode: "",
    salesMan: "",
  });
};
const handleReturn = () => {
  if (returnDialogFormData.returnMethod != "3" && returnProductData.value.length === 0)
    return ElMessage.error(`退货产品不能为空`);
  returnDialogFormData.discountAmount = discountRate.value;
  returnDialogFormData.isReturnOrder = 1;

  returnDialogFormData.salesOrderDetailList = returnProductData.value;
  returnDialogFormData.otherRef = returnDialogFormData.code;
  console.log(returnDialogFormData, "returnDialogFormData");

  orderReturnAPI
    .saveOrUpdateTSalesOrder(returnDialogFormData)
    .then((data) => {
      //修该订单状态为6
      ElMessage.success(`退货成功`);
    })
    .catch((err) => {})
    .finally(() => {
      handleCloseReturn();
      getOrderList();
    });
};
const cancelOrder = (order: Order) => {
  ElMessageBox.confirm(`是否取消订单`).then(() => {
    orderReturnAPI.delTSalesOrder(order.id).then(() => {
      ElMessage.success(`取消订单成功`);
      getOrderList();
    });
  });
};

//打开退货弹窗
const returnOrder = (order: Order) => {
  orderReturnAPI
    .getPage({
      pageSize: 1,
      pageNum: 1,
      otherRef: order.orderCode,
      isReturnOrder: 1,
      statusList: [0, 1, 2, 3, 4, 5],
    })
    .then(async (res) => {
      if (res.total !== 0) {
        ElMessage.error(`该订单已在退货列表，请等待审核员审核`);
      } else {
        showReturn.value = true;
        returnDialogFormData.code = order.orderCode;
        returnDialogFormData.customerName = customerName.value;
        returnDialogFormData.companyCode = getUserInfo.companyCode;
        returnDialogFormData.contractCode = order.contractCode;
        returnDialogFormData.salesMan = order.salesMan;
        const res = await getProductByOrder(order);
        console.log(res, "1212");
        returnProductData.value = res.detailList;
      }
    });
};
const returnDialogFormData = reactive<orderReturnInfo>({
  /** 订单编号 */
  code: "",
  otherRef: "",
  /** 订单类型 */
  docType: "",

  /** 客户编号 */
  companyCode: "",

  /** 客户名称 */
  customerName: "",
  discountRate: 0,
  discountAmount: 0,
  returnMethod: "1",
  remark: "",
  contractCode: "",
  salesMan: "",
});
const handleDelPro = (index: number) => {
  returnProductData.value.splice(index, 1);
};

onMounted(() => {
  getPackageType();
  getProductList();
  getProductType();
  getCustomerName(getUserInfo.companyCode);
  const cartData = sessionStorage.getItem("cart");
  if (cartData) {
    const cart = JSON.parse(cartData);
    //如果不是我的购物车，则不加载数据
    if (cart.userId !== getUserInfo.userId) return;
    cart.cartProduct.products.forEach((product: Product) => {
      myCart.addItem(product);
    });
  }
});
</script>

<style scoped>
.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: var(--el-fill-color-light);
  color: var(--el-text-color-secondary);
  font-size: 30px;
}
.el-image {
  width: 100%;
  height: 100%;
}
/* 按钮点击动画 */
@keyframes scaleClick {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(0.95);
  }
  100% {
    transform: scale(1);
  }
}

.add-animation {
  animation: scaleClick 0.3s ease;
}

/* 飞入购物车动画 */
@keyframes flyToCart {
  0% {
    opacity: 1;
    transform: translate(0, 0) scale(1);
  }
  100% {
    opacity: 0;
    transform: translate(100px, -100px) scale(0.3);
  }
}

.fly-effect {
  position: fixed;
  width: 40px;
  height: 40px;
  background: var(--el-color-primary);
  border-radius: 50%;
  animation: flyToCart 0.8s cubic-bezier(0.55, 0, 0.85, 0.44);
  pointer-events: none;
  z-index: 9999;
}
</style>
